#!/usr/bin/python
# -*- coding: utf-8 -*-
from datetime import date, datetime, timedelta

from jira import *

# JIRA API 中的日期格式
jira_time_fmt = "%Y-%m-%dT%H:%M:%S.%f%z"
def_time_fmt = "%Y-%m-%d %H:%M:%S"


def get_jira_client(server: str, auth: tuple = None):
    if not server or not auth or len(auth) != 2:
        raise RuntimeError('JIRA服务地址、用户名和密码不能为空')
    return JIRA(server=server, basic_auth=auth)


def last_30_days_section() -> tuple:
    return date.today() - timedelta(29), date.today() + timedelta(1)


def assemble_jql(users: tuple, project: str = 'IT', period: tuple = last_30_days_section()) -> str:
    """
    组装JIRA查询JQL
    """
    if users is None or project is None or period is None:
        raise RuntimeError('所有参数均不能为None')
    # user_str = "('" + "','".join(users) + "')"
    # return (f"project = {project} AND updated >= {period[0]} AND updated < {period[1]} "
    #         f"AND (watcher in {user_str} OR assignee in {user_str} OR creator in {user_str}) "
    #         f"ORDER BY updated")
    return (f"project = {project} AND updated >= {period[0]} AND updated < {period[1]} "
            f"ORDER BY updated ASC")


def fetch_worklog_list(client: JIRA, jql: str, fields: list, page_no: int = 0, page_count: int = 50, fetch_users: list = None) -> tuple:
    response = client.search_issues(jql_str=jql, fields=fields, startAt=page_no * page_count, maxResults=page_count, json_result=True)
    print("【JIRA第%s次查询】从第%s条开始，每页%s条，总量%s条，本次返回%s条" % (page_no + 1, response['startAt'], response['maxResults'], response['total'], len(response['issues'])))
    result_list = []
    if not response['issues']:
        return (page_no + 1) * page_count < response['total'], result_list
    for issue in response['issues']:
        worklogs = issue['fields']['worklog']['worklogs']
        if len(worklogs) < 1:
            print(issue['key'], '下没有工作日志')
            continue
        for worklog in worklogs:
            if worklog['author']['name'] not in fetch_users:
                print(issue['key'], '下', worklog['author']['displayName'], '的工作日志不需要处理')
                continue
            log_content = {
                'issue_key': issue['key'],
                'issue_type': issue['fields']['issuetype']['name'],
                'issue_status': issue['fields']['status']['name'],
                'issue_summary': issue['fields']['summary'],
                'issue_created': to_def_time_fmt(issue['fields']['created']),
                'issue_updated': to_def_time_fmt(issue['fields']['updated']),
                'issue_reporter': to_str(issue['fields']['reporter']['displayName']),
                'issue_creator': to_str(issue['fields']['creator']['displayName']),
                'issue_assignee': to_str(issue['fields']['assignee']['displayName']),
                'issue_desc': to_str(issue['fields']['description']),
                'id': worklog['id'],
                'author': worklog['author']['displayName'],
                'comment': to_str(worklog['comment']),
                'start_time': to_def_time_fmt(worklog['started']),
                'duration': sec_to_hour(worklog['timeSpentSeconds'])
            }
            print(issue['key'], '下', worklog['author']['displayName'], '的工作日志：', log_content)
            result_list.append(log_content)
    return (page_no + 1) * page_count < response['total'], result_list


def to_str(arg: str | None) -> str:
    if arg is None:
        return ''
    return arg


def to_def_time_fmt(arg: str | None):
    if arg is None:
        return datetime.min.strftime(def_time_fmt)
    return datetime.strptime(arg, jira_time_fmt).strftime(def_time_fmt)


def sec_to_hour(arg: int | None) -> int:
    if arg is None:
        return 0
    return int(arg / 3600)
